package com.itheima.service;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.Type.CommentType;
import com.itheima.api.CommentApi;
import com.itheima.api.UserInfoApi;
import com.itheima.api.VideoApi;
import com.itheima.domain.UserInfo;
import com.itheima.exception.BusinessException;
import com.itheima.interceptor.UserHolder;
import com.itheima.mongo.Comment;
import com.itheima.server.ErrorResult;
import com.itheima.template.OssTemplate;
import com.itheima.utils.Constants;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageResult;
import com.itheima.vo.Video;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    /**
     * 发布小视频
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //判断 是否有文件 图片
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }

        //将视频上传到FastDFS,获取访问URL
        //获取原文件名
        String filename = videoFile.getOriginalFilename();
        //根据.切割文件
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if(StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    public Integer like(String id) {
        //调用api 查询用户是否点赞
        Boolean hasvideo=videoApi.hasvideo(id,UserHolder.getUserId(), CommentType.LIKE);
        if (hasvideo){
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api 保存数据到comment
        Comment comment=new Comment();
        //动态id
        comment.setId(new ObjectId(id));
        //评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //用户id
        comment.setUserId(UserHolder.getUserId());
        //发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = videoApi.save2(comment);

        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey=Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer disLike(String disId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = videoApi.hasvideo(disId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞 抛出异常
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        //创建圈子交互表 查询数据
        Comment comment=new Comment();
        //写入获取的动态id
        comment.setPublishId(new ObjectId(disId));
        //写入获取的评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //写入当前评论人
        comment.setUserId(UserHolder.getUserId());
        //写入发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = videoApi.delete3(comment);

        //拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + disId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**
     *评论列表
     */
    public PageResult findSmallVideos(Integer page, Integer pagesize, String movementId) {
        //调用API查询评论列表
        List<Comment> list = videoApi.findComments(movementId, CommentType.COMMENT, page, pagesize);

        //判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }

        //提取所有的用户id,调用UserInfoAPI查询用户详情 查询查询集合  查询名称字段  查询类型
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        //查到了加入集合 没查到返回空  批量将用户信息加入集合
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);
        //构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        //遍历每个用户信息
        for (Comment video : list) {
            //遍历出每个评论用户
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                //将评论人与被评论的动态组合起来
                CommentVo vo = CommentVo.init(userInfo, video);
                //加入集合 组成完成
                vos.add(vo);
            }
        }
        //构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    //发布评论
    public void savecomments(String id, String comment) {
        //判断内容是否为空
        if (StringUtils.isEmpty(comment)){
            throw new BusinessException(ErrorResult.contentError());
        }

        //1、获取操作用户id  UserHolder获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment 评论类型
        Comment comment1 = new Comment();
        //动态id
        comment1.setPublishId(new ObjectId(id));
        //评论类型
        comment1.setCommentType(CommentType.COMMENT.getType());
        //评论内容
        comment1.setContent(comment);
        //评论人
        comment1.setUserId(userId);
        //发表时间
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = videoApi.save1(comment1);

    }

    /**
     * 评论喜欢点赞
     */
    public Integer commentsLike(String commentsId) {
        //调用api 查询用户是否点赞
        Boolean hasComment = videoApi.hasvideo(commentsId, UserHolder.getUserId(), CommentType.LIKE);
        if (hasComment){
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api 保存数据到Mongodb
        Comment comment=new Comment();
        //动态id
        comment.setPublishId(new ObjectId(commentsId));
        //评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //用户id
        comment.setUserId(UserHolder.getUserId());
        //发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = videoApi.save3(comment);
        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentsId;
        String hashKey=Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    /**
     * 评论取消点赞
     */
    public Integer commentsLike2(String commentsId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = videoApi.hasvideo(commentsId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞 抛出异常
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        //创建圈子交互表 查询数据
        Comment comment=new Comment();
        //写入获取的动态id
        comment.setPublishId(new ObjectId(commentsId));
        //写入获取的评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //写入当前评论人
        comment.setUserId(UserHolder.getUserId());
        //写入发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = videoApi.delete(comment);

        //拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentsId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    /**用户关注
     */
    public void likeUser(Long uid) {
        //1、调用API，保存喜欢数据(保存到MongoDB中)
        Boolean save = videoApi.saveOrUpdate(UserHolder.getUserId(), uid, true);
        if (!save) {
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (关注的集合，不关注的集合)
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + UserHolder.getUserId(), uid.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + UserHolder.getUserId(), uid.toString());

    }

    /**
     *取消关注
     */
    public void notLikeUser(Long uid) {
        Boolean save = videoApi.saveOrUpdate(UserHolder.getUserId(), uid, false);
        if (!save) {
            //失败
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY + UserHolder.getUserId(), uid.toString());
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserHolder.getUserId(), uid.toString());
    }
}
